#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 1e6 + 10, INF = 0x3f3f3f3f;

ll n, m;
priority_queue<ll, vector<ll>, greater<ll>> q;
ll b[N];

void solve()
{
    cin >> n >> m;
    for (ll i = 1;i <= n;i++) { ll x; cin >> x; q.push(x); }
    for (ll i = 1;i <= n;i++) cin >> b[i];
    sort(b + 1, b + n + 1, greater<ll>());

    ll ans = 0;
    for (ll i = 1;i <= n;i++) {

        while (!q.empty() && b[i] + q.top() < m) {
            ans += q.top();
            q.pop();
        }
        if (!q.empty()) {
            ans += (b[i] + q.top()) % m;
            q.pop();
        } else ans += b[i];
    }
    cout << ans << '\n';
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    cin>>T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}